﻿package znet

import (
	"errors"
	"sync"
	"zxGoServer/zinterface"
)

type ConnManager struct {
	zinterface.IConManager
	connections map[uint32]zinterface.IConnection // 管理连接
	connLock    sync.RWMutex                      // 读写连接的锁
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]zinterface.IConnection),
	}
}

func (connMgr *ConnManager) Add(conn zinterface.IConnection) {
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	connMgr.connections[conn.GetConnID()] = conn
}

func (connMgr *ConnManager) Remove(conn zinterface.IConnection) {
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	delete(connMgr.connections, conn.GetConnID())
}

func (connMgr *ConnManager) Get(connID uint32) (zinterface.IConnection, error) {
	connMgr.connLock.RLock()
	defer connMgr.connLock.RUnlock()
	conn, ok := connMgr.connections[connID]
	if ok {
		return conn, nil
	}
	return nil, errors.New("connection not found")
}

func (connMgr *ConnManager) Len() int {
	return len(connMgr.connections)
}

func (connMgr *ConnManager) ClearConn() {
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()
	for connID, conn := range connMgr.connections {
		conn.Stop()
		delete(connMgr.connections, connID)
	}
}
